package com.hui.config.security.authentication.dao;

import com.hui.entity.SystemUser;
import com.hui.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * AuthenticationProvider提供登录验证处理逻辑，我们实现该接口编写自己的验证逻辑。
 *
 * @author 廖云辉
 * @apiNote 缺省值：DaoAuthenticationProvider
 * @apiNote 认证由 AuthenticationManager 来管理的，但是真正进行认证的是 AuthenticationManager 中定义的 AuthenticationProvider。
 */
@Component
public class CustomerAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserService userService;

    /**
     * 登录验证处理
     *
     * @apiNote 验证成功返回成功后的token信息，返回null表示不验证，验证失败直接抛异常
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String loginName = authentication.getName();
        String password = authentication.getCredentials().toString();
        List<GrantedAuthority> grantedAuths = new ArrayList<>();
        if (vaildateUser(loginName, password, grantedAuths)) {
            return new UsernamePasswordAuthenticationToken(loginName, password, grantedAuths);
        } else {
            throw new BadCredentialsException("账号或密码错误");
        }

    }

    private boolean vaildateUser(String loginName, String password, List<GrantedAuthority> grantedAuths) {
        SystemUser user = userService.findByLoginName(loginName);
        if (user == null || loginName == null || password == null) {
            throw new UsernameNotFoundException("账号或密码错误");
        }
        if (password.equals(user.getPassword())) {//验证密码
             /*此处可以将角色信息放入grantedAuthority中*/
            if ("admin".equals(loginName)) {
                grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }
            if ("dev".equals(loginName)) {
                grantedAuths.add(new SimpleGrantedAuthority("ROLE_DEV"));
            }
            return true;
        }
        return false;
    }

    /**
     * supports函数用来指明该Provider是否适用于该类型的认证，如果不合适，则寻找另一个Provider进行验证处理。
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
